package bulletbehavior 
{
	import org.flixel.*;
	/**
	 * ...
	 * @author morgan
	 */
	public class HomeTargetBehavior extends BulletBehavior
	{
		public var target:FlxSprite;
		public var rotateSpeed:Number;
		public function HomeTargetBehavior(target:FlxSprite, rotateSpeed:Number = Math.PI) 
		{
			this.target = target;
			this.rotateSpeed = rotateSpeed;
		}
		
		override public function onUpdate(b:Bullet):void 
		{
			super.onUpdate(b);
			
			var dx:Number = (b.x + b.width / 2) - (target.x + target.width / 2);
			var dy:Number = (b.y + b.height / 2) - (target.y - target.height / 2);
			var tAngle:Number = Math.atan2(dy, dx);
			var bAngle:Number = Math.atan2(b.velocity.y, b.velocity.x);
			var len:Number = Math.sqrt(b.velocity.y * b.velocity.y + b.velocity.x * b.velocity.x);
			
			var sub:Number = tAngle - bAngle;
			if (sub < -Math.PI) { sub += Math.PI * 2; }
			else if (sub > Math.PI) { sub -= Math.PI * 2; }
			
			if (rotateSpeed < 0)
			{
				bAngle = tAngle + Math.PI;
			}
			else
			{
				if (sub < 0)
				{
					bAngle += rotateSpeed * FlxG.elapsed;
				}
				else
				{
					bAngle -= rotateSpeed * FlxG.elapsed;
				}
			}
			b.velocity.x = Math.cos(bAngle) * len;
			b.velocity.y = Math.sin(bAngle) * len;
			b.frame = (((bAngle / 6.2818 + 0.5) * 8) + 4) % 8;
			b.angle = 0;
			b.angularVelocity = 0;
		}
		
	}

}